﻿using System;
using System.Configuration;
using System.Data.SqlClient;

namespace ThirdPrize.Classes
{
    public sealed class Visit : IDisposable
    {
        public string UserId { get; set; }
        public string Votes { get; set; }
        public string Application { get; set; }
        public string Version { get; set; }
        public string Platform { get; set; }

        private readonly SqlConnection _myConn = new SqlConnection();

        public void Dispose()
        {
            _myConn.Dispose();
        }

        public Visit()
        {
            _myConn.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
            _myConn.Open();
        }

        public bool LogVisit()
        {
            bool result;

            //http://localhost:2789/code/registervisitv1.aspx?user=1234&appName=WebcomiX&appVersion=1.2
            string user = UserId;

            try
            {
                string strDel = String.Format(@"delete from Visits where UserId = '{0}' and AppName = '{1}'", user, Application);

                using (var myCom1 = new SqlCommand(strDel, _myConn))
                {
                    myCom1.ExecuteNonQuery();

                    using (var cmd = new SqlCommand())
                    {
                        string sql = "insert into Visits ";
                        sql += "values(@userid, @appName, @appVersion, @datevoted, @platform)";
                        cmd.CommandText = sql;
                        cmd.Parameters.AddWithValue("@userid", user);
                        cmd.Parameters.AddWithValue("@platform", Platform);
                        cmd.Parameters.AddWithValue("@appName", Application);
                        cmd.Parameters.AddWithValue("@appVersion", Version);
                        cmd.Parameters.AddWithValue("@datevoted", Convert.ToDateTime(DateTime.Now));

                        cmd.Connection = _myConn;
                        cmd.ExecuteNonQuery();
                    }
                    _myConn.Close();
                    result = true;

                }
            }
            catch (Exception)
            {
                result = false;
            }
            return result;
        }
    }
}